package com.aikon.wht.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by haitao.wang on 2016/11/30.
 */
public class TestOfAtomic<T> extends TestOfConcurrent{
    private AtomicInteger atomicInteger = new AtomicInteger(1);

    public AtomicInteger getAtomicInteger() {
        return atomicInteger;
    }

    public void setAtomicInteger(AtomicInteger atomicInteger) {
        this.atomicInteger = atomicInteger;
    }

    public static void main(String[] args) {
        ExecutorService es1 = Executors.newCachedThreadPool();
        TestOfAtomic testOfAtomic = new TestOfAtomic();
        es1.submit(new Thread(new T1(testOfAtomic.getAtomicInteger())));
        es1.submit(new Thread(new T2(testOfAtomic.getAtomicInteger())));
//        System.out.println(testOfAtomic.getAtomicInteger().get());
        es1.shutdown();
        while (true) {
            if (es1.isTerminated()) {
                System.out.println("All Over");
                break;
            }
        }
    }

    private static class T1 implements Runnable {

        private AtomicInteger ai = new AtomicInteger();

        T1(AtomicInteger ai) {
            this.ai = ai;
        }

        @Override
        public void run() {
            System.out.println("T1 starting");
            Thread.yield();
            while (ai.get() < 100) {
                System.out.println("T1    "+ai.get());
                ai.set(ai.get() + 1);
            }
        }
    }

    private static class T2 implements Runnable {

        private AtomicInteger ai = new AtomicInteger();

        T2(AtomicInteger ai) {
            this.ai = ai;
        }

        @Override
        public void run() {
            System.out.println("T2 starting");
            while (ai.get() < 100){
                System.out.println("T2    " + ai.get());
                ai.set(ai.get() + 1);
            }
        }
    }


}
